define(['jquery', 'backend', 'monContextMenu', 'upload'], function ($, Backend, monContextMenu, Upload) {
    var api = {
        query: '/admin/sys/filemanage',
        mkdir: '/admin/sys/filemanage/mkdir',
        rename: '/admin/sys/filemanage/rename',
        del: '/admin/sys/filemanage/del',
        upload: '/admin/sys/filemanage/upload',
    }
    var Controller = {
        index: function () {
            var dirItems = {
                'open': {
                    name: '打开目录',
                    icon: 'eye'
                }
            }
            var fileItems = {
                'read': {
                    name: '下载查看',
                    icon: 'eye'
                },
            }
            // 判断是否具有重命名权限
            if (window.setting.rename) {
                dirItems['rename'] = {
                    name: '重命名',
                    icon: 'text-width'
                }
                fileItems['rename'] = {
                    name: '重命名',
                    icon: 'text-width'
                }
            }
            // 判断是否具有删除权限
            if (window.setting.del) {
                dirItems['del'] = {
                    name: '删除',
                    icon: 'remove'
                }
                fileItems['del'] = {
                    name: '删除',
                    icon: 'remove'
                }
            }
            // 右键菜单
            monContextMenu.init({
                id: 'menu-dir',
                el: '.dir',
                items: dirItems,
                callback: Controller.api.monContextMenuCallback
            });
            monContextMenu.init({
                id: 'menu-file',
                el: '.file',
                items: fileItems,
                callback: Controller.api.monContextMenuCallback
            });
            // 全选checkbox
            $(document).on('click', '#selectedAll', function () {
                $('#table tbody td input[type="checkbox"]').prop("checked", $(this).prop("checked"));
            });
            // 获取数据
            Controller.api.queryContent(window.setting.root)
            // 打开目录
            $(document).on('click', '.opendir', function () {
                var nowPath = Controller.api.getNowPath()
                var dir = $.trim($(this).text())
                Controller.api.queryContent(nowPath + '/' + dir)
            })
            // 刷新
            $(document).on('click', '.btn-refresh', function () {
                var nowPath = Controller.api.getNowPath()
                Controller.api.queryContent(nowPath)
            })
            // 返回上一级
            $(document).on('click', '.btn-return', function () {
                var nowPath = Controller.api.getNowPath()
                var arr = nowPath.split('/');
                arr.pop()
                Controller.api.queryContent(arr.join('/'))
            })
            // 新建文件夹
            $(document).on('click', '.btn-mkdir', function () {
                Layer.prompt({
                    id: 'mkdir',
                    title: '请输入目录名称',
                }, function (name, index) {
                    Layer.close(index);
                    Controller.api.mkdir(name)
                });
            })
            // 批量删除
            $(document).on('click', '.btn-remove', function () {
                var paths = Controller.api.getSelected()
                if (paths.length < 1) {
                    Layer.alert('请先勾选要删除的文件目录', {
                        icon: 2,
                        title: '错误'
                    });
                    return;
                }
                var pathMsg = paths.join('<br/>')
                Layer.confirm('确定要删除以下目录文件么？<br/>' + pathMsg, function (index) {
                    Layer.close(index)
                    Controller.api.del(paths)
                })
            })
            // 文件上传
            Upload.render({
                elem: '.btn-upload',
                url: api.upload,
                data: {
                    path: function () {
                        return Controller.api.getNowPath()
                    }
                },
                exts: '',
                done: function (ret, index, upload) {
                    if (ret.code != '1') {
                        Toastr.error(ret.msg);
                        return;
                    }
                    var url = ret.data.url
                    Controller.api.queryContent(Controller.api.getNowPath())
                }
            });
        },

        api: {
            // 右键菜单回调
            monContextMenuCallback: function (data) {
                var type = data.type
                switch (type) {
                    case 'open':
                        var nowPath = Controller.api.getNowPath()
                        var dir = $.trim($(data.elem).data('name'))
                        Controller.api.queryContent(nowPath + '/' + dir)
                        break;
                    case 'read':
                        var nowPath = Controller.api.getNowPath()
                        var filename = $.trim($(data.elem).data('name'))
                        var root = window.setting.root
                        var cdn = window.setting.cdn
                        var url = nowPath.replace(root, cdn) + '/' + filename
                        window.open(url)
                        break;
                    case 'rename':
                        var oldname = $(data.elem).data('name');
                        Layer.prompt({
                            id: 'rename',
                            title: '请输出重命名的名称',
                        }, function (newname, index) {
                            Layer.close(index);
                            Controller.api.rename(oldname, newname)
                        });
                        break;
                    case 'del':
                        var nowPath = Controller.api.getNowPath()
                        var name = $(data.elem).data('name');
                        Layer.confirm('确定要删除' + name + '么？', function (index) {
                            Layer.close(index)
                            Controller.api.del(nowPath + '/' + name)
                        })
                        break;
                }
            },
            // 设置路径
            setNowPath: function (path) {
                $('#nowPath').text(path)
            },
            // 后去当前路径
            getNowPath: function () {
                return $.trim($('#nowPath').text())
            },
            // 获取选中的checkbox
            getSelected: function () {
                var basePath = Controller.api.getNowPath();
                var data = [];
                $('#table tbody td input[type=checkbox]:checked').each(function (i, e) {
                    var name = $(e).parents('tr').data('name');
                    data.push(basePath + '/' + name)
                })
                return data;
            },
            // 获取数据
            queryContent: function (path) {
                Mon.api.ajax({
                    url: api.query,
                    data: {
                        path: path,
                    },
                }, function (data, ret) {
                    // 设置路径
                    Controller.api.setNowPath(path)
                    // 解析数据
                    var html = []
                    if (data.length > 0) {
                        for (var i = 0, l = data.length; i < l; i++) {
                            var item = data[i],
                                fileTxt = '',
                                className = '';
                            // 解析文件名
                            if (item.is_dir) {
                                className = 'dir'
                                fileTxt = '<i class="fa fa-folder" style="color: #99CC99;"></i> <a href="javascript:void(0);" class="opendir">' + item.filename + '</a>'
                            } else if (['ico', 'png', 'jpg', 'jpeg', 'gif'].indexOf(item.filetype) >= 0) {
                                className = 'file'
                                fileTxt = '<i class="fa fa-picture-o"></i> <span>' + item.filename + '</span>'
                            } else {
                                className = 'file'
                                fileTxt = '<i class="fa fa-file-o"></i> <span>' + item.filename + '</span>'
                            }

                            var temp = '<tr class="item ' + className + '" data-name="' + item.filename + '"">\
                                            <td><input type="checkbox" name="selected" lay-skin="primary"></td>\
                                            <td>' + fileTxt + '</td>\
                                            <td>' + Controller.api.format.parseByte(item.filesize) + '</td>\
                                            <td>' + item.datetime + '</td>\
                                        </tr>'

                            html.push(temp)
                        }
                    } else {
                        var temp = '<tr><td colspan="4" style="text-align:center;">路径暂无内容</td></tr>'
                        html.push(temp)
                    }

                    $('#table tbody').html(html.join(' '))
                    return false
                })
            },
            // 创建目录
            mkdir: function (dir) {
                var nowPath = Controller.api.getNowPath();
                var path = nowPath + '/' + dir
                Mon.api.ajax({
                    url: api.mkdir,
                    data: {
                        path: path,
                    },
                }, function (data, ret) {
                    Controller.api.queryContent(nowPath)
                })
            },
            // 重命名
            rename: function (oldname, newname) {
                var path = Controller.api.getNowPath()
                Mon.api.ajax({
                    url: api.rename,
                    data: {
                        path: path,
                        oldname: oldname,
                        newname: newname
                    },
                }, function (data, ret) {
                    Controller.api.queryContent(path)
                })
            },
            // 删除文件目录
            del: function (path) {
                var nowPath = Controller.api.getNowPath();
                Mon.api.ajax({
                    url: api.del,
                    data: {
                        path: path,
                    },
                }, function (data, ret) {
                    Controller.api.queryContent(nowPath)
                })
            },
            format: {
                // 格式化文件大小
                parseByte: function (size) {
                    if (size == 0) {
                        return '-';
                    }
                    var type = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
                    var pos = 0;
                    while (size >= 1024) {
                        size /= 1024;
                        pos++;
                    }

                    return (Math.round(size * 100) / 100) + ' ' + type[pos]
                }
            }
        }
    };
    return Controller;
});